package com.qqclient.serivce;

import com.qqcommon.Message;
import com.qqcommon.MessageType;

import java.io.*;
import java.util.Date;

public class FileClientService {
    /**
     *
     * @param src //源文件路径
     * @param dest //目标路径
     * @param senderId //发送者
     * @param getterId //接收者
     *
     */
    public void sendfileToOne(String src,String dest,String senderId, String getterId){
        Message message = new Message();
        message.setMesType(MessageType.MESSAGE_FILE_MES);
        message.setSender(senderId);
        message.setGetter(getterId);
        message.setSrc(src);
        message.setDest(dest);
        message.setSendTime(new Date().toString());//发送时间

        //文件读取
        FileInputStream fileInputStream = null;
        byte[] fileBytes = new byte[(int)new File(src).length()];

        try {
            fileInputStream = new FileInputStream(src);
            fileInputStream.read(fileBytes);
            message.setFileBytes(fileBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (fileInputStream != null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("\n"+senderId+"给"+getterId+"发送文件："+src+"到对方："+dest);
        //发送
        try {
            ObjectOutputStream oos = new ObjectOutputStream
                    (ManageClientConnectServerThread.getClientConnectServerThread(senderId).getSocket().getOutputStream());
            oos.writeObject(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
